package com.call.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.call.Constants;
import com.call.R;
import com.call.activity.MainActivity;
import com.call.data.MissCallData;
import com.call.widget.WidgetProvider;


public class MissCallAndPhoneNumberService extends Service{
	
	private static final String TAG = "MissCallAndPhoneNumberService";
	private MissCallData m_objMissCallData;
	
	private static MissCallAndPhoneNumberService instance = null;

	public static boolean isInstanceCreated() { 
	      return instance != null; 
	}//met
	
	private class ServiceBinder extends Binder implements IMissCallAndPhoneNumberService{
				
		public void AddMissCallInfo(String phoneNumber,long time)
		{
			addMissCall(phoneNumber, time);
		}

		public void DeleteMissCallInfo(int id) {
			m_objMissCallData.delete(MissCallData.TableColumns._ID + " = "+id, null);
			//Log.i(Constants.Tag, "delete miss call id: "+ id +" info from service");
		}

		public Cursor GetMissCallInfo() {
			Cursor res = m_objMissCallData.query(null, null, null, MissCallData.TableColumns.CallTime + " DESC ", 0, Integer.MAX_VALUE);
			//Log.i(Constants.Tag, "get miss call info from service");
			return res;
		}
	}
	private boolean isMissedCall(String phoneNumber)
	{
		final String[] projection = null;
		final String selection = null;
		final String[] selectionArgs = null;
		final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
		Cursor cursor = null;
	    boolean missCall = false;
		try{
		    cursor = getContentResolver().query(
		            Uri.parse("content://call_log/calls"),
		            projection,
		            selection,
		            selectionArgs,
		            sortOrder);
		    Long time = (long) 0;
		    while (cursor.moveToNext())
		    {
		    	String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
		        String callType = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
		        if (callNumber.equals(phoneNumber))
		        {
		        	Log.v("DEBUG", callNumber);
		        	Long cTime = Long.parseLong( cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE)));
		        	if (cTime < time)
		        		break;
		        	time = cTime;
		        	missCall = Integer.parseInt(callType) == android.provider.CallLog.Calls.MISSED_TYPE;
//	                  {
//	                	  return true;
//	                  }
//	                  else if(Integer.parseInt(callType) == android.provider.CallLog.Calls.INCOMING_TYPE)
//	                  {
//		                  Log.v("DEBUG","No Missed Call: INCOMING_TYPE " + callNumber);
//	                	  cursor.close();
//	                	  return false;		                	  
//	                  }
//	                  else
//	                  {
//		                  Log.v("DEBUG","NO Missed Call: " + callNumber);
//	                	  cursor.close();
//	                	  return false;	                	  
//	                  }
		        }
		    }
		}catch(Exception ex){
		     Log.e("ERROR: ",  ex.toString());
		     missCall = false;
		}
		cursor.close();
		return missCall;
	}
	private void addMissCall(String phoneNumber,long time)
	{
		if (!isMissedCall(phoneNumber))
			return;
    	Log.v("DEBUG", "Missed Call: " + phoneNumber);

		NotificationManager notificationManager;
		Notification notification = null;
		PendingIntent pendingIntent;
		ContentValues values = new ContentValues();
		
		values.put(MissCallData.TableColumns.CallTime, time);
		values.put(MissCallData.TableColumns.CallNumber, phoneNumber);

		m_objMissCallData.insert(values);
		
		//Show message in the notify bar.
		notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		notification = new Notification();
        
		Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(Intent.ACTION_VIEW);
        notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		notification.icon = R.drawable.attention;  
		notification.defaults = Notification.DEFAULT_SOUND;
		
		//Click it and it will disappear
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.setLatestEventInfo(this, "Missed Call", phoneNumber, pendingIntent);
		notification.tickerText = "Missed call from " + phoneNumber;
		notificationManager.notify(Constants.notificationID, notification);
	}
	
	private ServiceBinder serviceBind = new ServiceBinder();
	private PhoneDialStateListener mPhoneStateListener;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return serviceBind;
	}
	
	@Override
	public void onCreate()
	{
		super.onCreate();
		
		instance = this;
		
		Log.v(TAG,"onCreate");
		
		//initialize service
		m_objMissCallData = MissCallData.GetMissCallData(this, Constants.MISSCALL_TABLENAME);
		mPhoneStateListener = new PhoneDialStateListener(serviceBind);
		
		// register phone dial state listener.
		TelephonyManager mTelephonyManager;
        mTelephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        //Log.i(Constants.Tag, "Add Miss call and phone number service.\n");
	}
	
//
//    private void UpdateWidget()
//    {
//    	//if (isServiceRunning())
//    	//	WidgetProvider.startService = true;
//    	//else WidgetProvider.startService = false;
//    	
//    	Log.v(TAG, "UpdateWidget" + String.valueOf(WidgetProvider.startService) );
//    	
//        Intent i = new Intent(this, WidgetProvider.class); 
//        i.setAction(WidgetProvider.UPDATE_ACTION); 
//        sendBroadcast(i); 
//    }
	
	@Override
	public void onDestroy()
	{
		Log.v(TAG,"onDestroy");
		
		instance = null;
		
		//UpdateWidget();
		
		//unregister phone dial state listener.
		TelephonyManager telephonyManager;
		telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
	}
}
